package com.ruoyi.dev.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.dev.mapper.DevDatasetMapper;
import com.ruoyi.dev.domain.DevDataset;
import com.ruoyi.dev.service.IDevDatasetService;

/**
 * 数据集Service业务层处理
 * 
 * @author yepanpan
 * @date 2025-01-22
 */
@Service
public class DevDatasetServiceImpl implements IDevDatasetService 
{
    private static final Logger log = LoggerFactory.getLogger(DevDatasetServiceImpl.class);

    @Autowired
    private DevDatasetMapper devDatasetMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;



    @Override
    @DataScope(deptAlias = "t", userAlias = "t")
    public Object queryDs(DevDataset devDataset) {
        DevDataset ds = selectDevDatasetByCode(devDataset.getCode());
        if(ds == null){
            throw new ServiceException("非法请求!");
        }
        String sql = ds.getSqls();

        //权限范围
        sql = sql.replaceAll("\\$\\{dataScope\\}", devDataset.getParams().get("dataScope").toString());
        //当前用户
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        sql = sql.replaceAll("\\$\\{userId\\}", sysUser.getUserId().toString());
        sql = sql.replaceAll("\\$\\{deptId\\}", sysUser.getDeptId().toString());

        //参数
        Object pv = devDataset.getParams().get(ds.getSearchField());
        if(pv != null && StringUtils.isNotEmpty(pv.toString())){
            String sv = pv.toString();
            if("range".equalsIgnoreCase(ds.getSearchExp())){
                sql = "SELECT * FROM ( "+sql+" ) t WHERE "+ds.getSearchField()+" between " + sv.replace(",", " AND ");
            }else{
                sql = "SELECT * FROM ( "+sql+" ) t WHERE "+ds.getSearchField()+" = " + sv;
            }
        }

        //过滤参数
        pv = devDataset.getParams().get("label");
        if(pv != null && StringUtils.isNotEmpty(pv.toString())){
            sql = "SELECT * FROM ( "+sql+" ) t WHERE label like concat('%', '" + pv.toString() + "','%')";
        }
        pv = devDataset.getParams().get("value");
        if(pv != null && StringUtils.isNotEmpty(pv.toString())){
            sql = "SELECT * FROM ( "+sql+" ) t WHERE value = '" + pv.toString() + "'";
        }

        try {
            if(DevDataset.TYPE_SUM.equalsIgnoreCase(ds.getType())){
                Map<String, Object> data = jdbcTemplate.queryForMap(sql + " limit 1");
                //如果是汇总计算查询，返回第一个结果，没有结果返回0
                return data == null || data.isEmpty() ? 0 : data.get("value");
            }else if(DevDataset.TYPE_MAP.equalsIgnoreCase(ds.getType())){
                //如果是映射，就生成label->value的map
                Map<String, Object> data = new HashMap<>();
                jdbcTemplate.query(sql+" limit 1000", (rs)->{
                    data.put(rs.getString("label"), rs.getFloat("value"));
                });
                return data;
            }else{
                List<Map> list = new ArrayList<>();
                jdbcTemplate.query(sql+" limit 1000", (rs)->{
                    Map<String, Object> data = new HashMap<>();
                    for(int i=1;i<=rs.getMetaData().getColumnCount();i++){
                        data.put(rs.getMetaData().getColumnLabel(i), rs.getObject(i));
                    }
                    list.add(data);
                });
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询数据集
     *
     * @param code 数据集代码
     * @return 数据集
     */
    @Override
    public DevDataset selectDevDatasetByCode(String code){
        return devDatasetMapper.selectDevDatasetByCode(code);
    }


    /**
     * 查询数据集
     * 
     * @param id 数据集主键
     * @return 数据集
     */
    @Override
    public DevDataset selectDevDatasetById(Long id)
    {
        return devDatasetMapper.selectDevDatasetById(id);
    }

    /**
     * 查询数据集列表
     * 
     * @param devDataset 数据集
     * @return 数据集
     */
    @Override
    public List<DevDataset> selectDevDatasetList(DevDataset devDataset)
    {
        return devDatasetMapper.selectDevDatasetList(devDataset);
    }

    /**
     * 新增数据集
     * 
     * @param devDataset 数据集
     * @return 结果
     */
    @Override
    public int insertDevDataset(DevDataset devDataset)
    {
        devDataset.setCreateTime(DateUtils.getNowDate());
        return devDatasetMapper.insertDevDataset(devDataset);
    }

    /**
     * 修改数据集
     * 
     * @param devDataset 数据集
     * @return 结果
     */
    @Override
    public int updateDevDataset(DevDataset devDataset)
    {
        devDataset.setUpdateTime(DateUtils.getNowDate());
        return devDatasetMapper.updateDevDataset(devDataset);
    }

    /**
     * 批量删除数据集
     * 
     * @param ids 需要删除的数据集主键
     * @return 结果
     */
    @Override
    public int deleteDevDatasetByIds(Long[] ids)
    {
        return devDatasetMapper.deleteDevDatasetByIds(ids);
    }

    /**
     * 删除数据集信息
     * 
     * @param id 数据集主键
     * @return 结果
     */
    @Override
    public int deleteDevDatasetById(Long id)
    {
        return devDatasetMapper.deleteDevDatasetById(id);
    }


}
